<!DOCTYPE html>
<html>
<head>
    

    

    
<!-- Baidu Tongji -->
<script>var _hmt = _hmt || []</script>
<script async src="//hm.baidu.com/hm.js?a7c05ce530152d9866930ef4850ee566"></script>
<!-- End Baidu Tongji -->




    <meta charset="utf-8">
    
    
    
    <title>shiro(三) 身份认证 | 神奇的鸭鸭の码农库 | 新知识要不断的总结记录成笔记，要多写，多画，能够清晰透彻的将知识讲给别人听，才是达到理解的层次。</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#765959">
    
    
    <meta name="keywords" content="安全">
    <meta name="description" content="学习来源：Apache Shiro Authentication 认证身份验证的过程–也就是证明一个用户的真实身份。为了证明用户身份，需要提供系统理解和相信的身份信息和证据。  用户需要提供用户的身份(principals)和证明(credentials)给shiro，从而来判定是否能通过验证：  Principals(身份)： 是Subject的”标识属性”，一般使用用户名或邮箱地址，唯一即可。">
<meta name="keywords" content="安全">
<meta property="og:type" content="article">
<meta property="og:title" content="shiro(三) 身份认证">
<meta property="og:url" content="http://magic_duck.oschina.io/2017/12/05/shiro03/index.html">
<meta property="og:site_name" content="神奇的鸭鸭の码农库">
<meta property="og:description" content="学习来源：Apache Shiro Authentication 认证身份验证的过程–也就是证明一个用户的真实身份。为了证明用户身份，需要提供系统理解和相信的身份信息和证据。  用户需要提供用户的身份(principals)和证明(credentials)给shiro，从而来判定是否能通过验证：  Principals(身份)： 是Subject的”标识属性”，一般使用用户名或邮箱地址，唯一即可。">
<meta property="og:image" content="http://magic_duck.oschina.io/image/shiro_authentication.png">
<meta property="og:image" content="http://magic_duck.oschina.io/image/shiro_authentication_sequence.png">
<meta property="og:updated_time" content="2017-12-05T09:59:44.484Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="shiro(三) 身份认证">
<meta name="twitter:description" content="学习来源：Apache Shiro Authentication 认证身份验证的过程–也就是证明一个用户的真实身份。为了证明用户身份，需要提供系统理解和相信的身份信息和证据。  用户需要提供用户的身份(principals)和证明(credentials)给shiro，从而来判定是否能通过验证：  Principals(身份)： 是Subject的”标识属性”，一般使用用户名或邮箱地址，唯一即可。">
<meta name="twitter:image" content="http://magic_duck.oschina.io/image/shiro_authentication.png">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="/css/style.css?v=1.4.3">
    <script>window.lazyScripts=[]</script>
</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">神奇的鸭鸭</h5>
          <a href="mailto:702038338@qq.com" title="702038338@qq.com" class="mail">702038338@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                归档
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://git.oschina.net/magic_duck" target="_blank" >
                <i class="icon icon-lg icon-gg-circle"></i>
                码云
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://www.zhihu.com/people/shen-qi-de-ya-ya" target="_blank" >
                <i class="icon icon-lg icon-twitter"></i>
                知乎
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/404.html"  >
                <i class="icon icon-lg icon-link"></i>
                404页面测试
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">shiro(三) 身份认证</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">shiro(三) 身份认证</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-12-04T16:02:00.000Z" itemprop="datePublished" class="page-time">
  2017-12-05
</time>


            
        </h5>
    </div>

    

</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#Authentication-认证"><span class="post-toc-number">1.</span> <span class="post-toc-text">Authentication 认证</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Authenticating-Subjects"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">Authenticating Subjects</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#第一步：收集用户身份和证明"><span class="post-toc-number">1.1.1.</span> <span class="post-toc-text">第一步：收集用户身份和证明</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#第二步：提交身份和证明"><span class="post-toc-number">1.1.2.</span> <span class="post-toc-text">第二步：提交身份和证明</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#第三步：处理成功或失败"><span class="post-toc-number">1.1.3.</span> <span class="post-toc-text">第三步：处理成功或失败</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Remembered-vs-Authenticated"><span class="post-toc-number">1.2.</span> <span class="post-toc-text">Remembered vs. Authenticated</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#An-illustrating-example-一个例子说明"><span class="post-toc-number">1.3.</span> <span class="post-toc-text">An illustrating example 一个例子说明</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Logging-Out-退出登录"><span class="post-toc-number">1.4.</span> <span class="post-toc-text">Logging Out 退出登录</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#Authentication-Sequence-身份认证流程"><span class="post-toc-number">2.</span> <span class="post-toc-text">Authentication Sequence 身份认证流程</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Authenticator"><span class="post-toc-number">2.1.</span> <span class="post-toc-text">Authenticator</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#AuthenticationStrategy"><span class="post-toc-number">2.2.</span> <span class="post-toc-text">AuthenticationStrategy</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Realm-验证的顺序"><span class="post-toc-number">2.3.</span> <span class="post-toc-text">Realm 验证的顺序</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#隐含的顺序"><span class="post-toc-number">2.3.1.</span> <span class="post-toc-text">隐含的顺序</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#Explicit-Ordering明确的顺序"><span class="post-toc-number">2.3.2.</span> <span class="post-toc-text">Explicit Ordering明确的顺序</span></a></li></ol></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#Final-Tutorial-class"><span class="post-toc-number">3.</span> <span class="post-toc-text">Final Tutorial class</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#MyRealm1-2-3"><span class="post-toc-number">3.1.</span> <span class="post-toc-text">MyRealm1,2,3</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#ini配置文件"><span class="post-toc-number">3.2.</span> <span class="post-toc-text">ini配置文件</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#测试类AuthenticatorTest"><span class="post-toc-number">3.3.</span> <span class="post-toc-text">测试类AuthenticatorTest</span></a></li></ol></li></ol>
        </nav>
    </aside>
    
<article id="post-shiro03"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">shiro(三) 身份认证</h1>
        <div class="post-meta">
            <time class="post-time" title="2017年12月05日 0:02" datetime="2017-12-04T16:02:00.000Z"  itemprop="datePublished">2017-12-05</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <p>学习来源：<strong><a href="http://shiro.apache.org/introduction.html" target="_blank" rel="external">Apache Shiro</a></strong></p>
<h2 id="Authentication-认证"><a href="#Authentication-认证" class="headerlink" title="Authentication 认证"></a>Authentication 认证</h2><p>身份验证的过程–也就是证明一个用户的真实身份。为了证明用户身份，需要提供系统理解和相信的身份信息和证据。</p>
<p><img src="/image/shiro_authentication.png" alt="1"></p>
<p>用户需要提供用户的身份(principals)和证明(credentials)给shiro，从而来判定是否能通过验证：</p>
<ul>
<li><strong>Principals(身份)：</strong> 是Subject的”标识属性”，一般使用用户名或邮箱地址，唯一即可。</li>
<li><strong>Primary Principal(最主要的身份)：</strong> 一个主体可以有多个Principal，但只有一个Primary Principal。</li>
<li><strong>Credentials(证明):</strong> 证明/凭证，即只有主体知道的安全值，如密码/数字证书等。</li>
</ul>
<p>最常见的principals和credentials组合就是用户名/密码了。接下来先进行一个基本的身份认证。</p>
<h3 id="Authenticating-Subjects"><a href="#Authenticating-Subjects" class="headerlink" title="Authenticating Subjects"></a>Authenticating Subjects</h3><p>Subject 验证的过程可以有效地划分分以下三个步骤：</p>
<ol>
<li>收集 Subject 提交的身份和证明</li>
<li>向Authentication提交身份和证明；</li>
<li>如果提交的内容正确，允许访问，否则重新尝试验证或阻止访问</li>
</ol>
<p>下面的代码示范了 Shiro API 如何实现这些步骤：</p>
<h4 id="第一步：收集用户身份和证明"><a href="#第一步：收集用户身份和证明" class="headerlink" title="第一步：收集用户身份和证明"></a>第一步：收集用户身份和证明</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//最常用的情况是 username/password 对:</span></div><div class="line">UsernamePasswordToken token = <span class="keyword">new</span> UsernamePasswordToken(username, password);</div><div class="line"><span class="comment">//”Remember Me” 功能是内建的</span></div><div class="line">token.setRememberMe(<span class="keyword">true</span>);</div></pre></td></tr></table></figure>
<p>在这里我们使用UsernamePasswordToken，支持所有常用的用户名/密码验证途径，这是一个org.apache.shiro.authc.AuthenticationToken接口的实现，这个接口被Shiro认证系统用来提交身份和证明。你可以随自己喜欢构造和引用 AuthenticationToken实例。</p>
<p>这个例子同样显示我们希望 Shiro 在尝试验证时执行 “Remember Me” 服务，这确保 Shiro 在用户今后返回系统时能记住他们的身份，我们会在以后的章节讨论 “Remember Me” 服务。</p>
<h4 id="第二步：提交身份和证明"><a href="#第二步：提交身份和证明" class="headerlink" title="第二步：提交身份和证明"></a>第二步：提交身份和证明</h4><p>当身份和证明住处被收集并实例化为一个AuthenticationToken（认证令牌）后，我们需要向Shiro提交令牌以执行真正的验证尝试：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">Subject currentUser = SecurityUtils.getSubject();</div><div class="line">currentUser.login(token);</div></pre></td></tr></table></figure>
<p>当login函数没有返回信息时表明验证通过了。程序可以继续运行，此时执行SecurityUtils.getSubject()将返回验证后的Subject实例，subject.isAuthenticated())将返回true。</p>
<h4 id="第三步：处理成功或失败"><a href="#第三步：处理成功或失败" class="headerlink" title="第三步：处理成功或失败"></a>第三步：处理成功或失败</h4><p>同时我们还可以捕获login失败的异常，Shiro拥有丰富的运行期异常AuthenticationException可以精确标明为何验证失败，你可以将login放入到try/catch块中并捕获所有你想捕获的异常并对它们做出处理。如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">try</span> &#123;</div><div class="line">    currentUser.login(token);</div><div class="line">&#125; <span class="keyword">catch</span> ( UnknownAccountException uae ) &#123; ...</div><div class="line">&#125; <span class="keyword">catch</span> ( IncorrectCredentialsException ice ) &#123; ...</div><div class="line">&#125; <span class="keyword">catch</span> ( LockedAccountException lae ) &#123; ...</div><div class="line">&#125; <span class="keyword">catch</span> ( ExcessiveAttemptsException eae ) &#123; ...</div><div class="line">&#125; ... 捕获你自己的异常 ...</div><div class="line">&#125; <span class="keyword">catch</span> ( AuthenticationException ae ) &#123;</div><div class="line">    <span class="comment">//未预计的错误?</span></div><div class="line">&#125;</div><div class="line"><span class="comment">//没问题，继续</span></div></pre></td></tr></table></figure>
<h3 id="Remembered-vs-Authenticated"><a href="#Remembered-vs-Authenticated" class="headerlink" title="Remembered vs. Authenticated"></a>Remembered vs. Authenticated</h3><p>如上例所示，Shiro 支持在登录过程中执行”remember me”，在此值得指出，一个已记住的 Subject（remembered Subject）和一个正常通过认证的 Subject（authenticated Subject）在 Shiro 是完全不同的。</p>
<ul>
<li><strong>记住的（Remembered）：</strong> 一个被记住的Subject没有已知身份（也就是说subject.getPrincipals())返回空），但是它的身份被先前的认证过程记住，并存于先前session中，一个被认为记住的对象在执行subject.isRemembered())返回真。</li>
<li><strong>已验证（Authenticated）：</strong> 一个被验证的 Subject 是成功验证后（如登录成功）并存于当前 session 中，一个被认为验证过的对象调用subject.isAuthenticated()) 将返回真。</li>
</ul>
<p>当一个用户仅仅在上一次与程序交互时被记住，证明的状态已经不存在了：被记住的身份只是给系统一个信息这个用户可能是谁，但不确定，没有办法担保这个被记住的 Subject 是所要求的用户，一旦这个 Subject 被验证通过，他们将不再被认为是记住的因为他们的身份已经被验证并存于当前的session中。</p>
<p>所以尽管程序大部分情况下仍可以针对记住的身份执行用户特定的逻辑，比如说自定义的视图，但不要执行敏感的操作直到用户成功执行身份验证使其身份得到确定。</p>
<p>例如，检查一个 Subject 是否可以访问金融信息应该取决于是否被验证（isAuthenticated()）而不是被记住（isRemembered()），要确保该Subject 是所需的和通过身份验证的。</p>
<h3 id="An-illustrating-example-一个例子说明"><a href="#An-illustrating-example-一个例子说明" class="headerlink" title="An illustrating example 一个例子说明"></a>An illustrating example 一个例子说明</h3><p>下面是一个非常常见的场景帮助说明被记住和被验证之间差别为何重要。</p>
<p>假设你使用Amazon.com，你已经成功登录并且在购物蓝中添加了一些书籍，但你由于临时要参加一个会议，匆忙中你忘记退出登录，当会议结束，回家的时间到了，于是你离开了办公室。</p>
<p>第二天当你回到工作，你意识到你没有完成你的购买动作，于是你回到Amazon.com，这时，Amazon.com“记得”是是，通过你的名字向你打招呼，仍旧给你提供个性化的图书推荐，对于Amazon.com，subject.isRemembered() 将返回真。</p>
<p>但是当你想访问你帐号的信用卡信息完成图书购买的时候会怎样呢？虽然Amazon.com “记住”了你（isRemembered() == true），它不能担保你就是你（也许是正在使用你计算机的同事）。</p>
<p>于是，在你执行像使用信用卡信息之类的敏感操作之前，Amazon.com强制你登录以使他们担保你的身份，在你登录之后，你的身份已经被验证，对于Amazon.com，isAuthenticated()将返回真。</p>
<p>这类情景经常发生，所以 Shiro 加入了该功能，你可以在你的程序中使用。现在是使用 isRemembered() 还是使用 isAuthenticated() 来定制你的视图和工作流完全取决于你自己，但 Shiro 维护这种状态基础以防你可能会需要。</p>
<h3 id="Logging-Out-退出登录"><a href="#Logging-Out-退出登录" class="headerlink" title="Logging Out 退出登录"></a>Logging Out 退出登录</h3><p>与验证相对的是释放所有已知的身份信息，当 Subject 与程序不再交互了，你可以调用 subject.logout() 丢掉所有身份信息。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">currentUser.logout(); <span class="comment">//清除验证信息，使 session 失效</span></div></pre></td></tr></table></figure>
<p>当你调用 logout，任何现存的 session 将变为不可用并且所有的身份信息将消失（如：在 web 程序中，RememberMe 的 Cookie 信息同样被删除）。</p>
<blockquote>
<p>Web 程序需注意：因为在 Web 程序中记住身份信息往往使用 Cookies，而 Cookies 只能在 Response 提交时才能被删除，所以强烈要求在为最终用户调用subject.logout() 之后立即将用户引导到一个新页面，确保任何与安全相关的 Cookies 如期删除，这是 Http 本身 Cookies 功能的限制而不是 Shiro 的限制。</p>
</blockquote>
<hr>
<h2 id="Authentication-Sequence-身份认证流程"><a href="#Authentication-Sequence-身份认证流程" class="headerlink" title="Authentication Sequence 身份认证流程"></a>Authentication Sequence 身份认证流程</h2><p>直到现在，我们只看到如何在程序代码中验证一个 Suject，现在我们看一下当一个验证发生时 Shiro 内部发生了什么。</p>
<p>我们仍使用之前在架构Architecture章节里见到过的架构图，仅将左侧跟认证相关的组件高亮，每一个数字代表认证中的一个步骤：</p>
<p><img src="/image/shiro_authentication_sequence.png" alt="2"></p>
<ol>
<li>首先调用Subject.login(token)进行登录，其会自动委托给Security Manager，调用之前必须通过SecurityUtils. setSecurityManager()设置；</li>
<li>SecurityManager负责真正的身份验证逻辑；它会委托给Authenticator进行身份验证；</li>
<li>Authenticator才是真正的身份验证者，Shiro API中核心的身份认证入口点，此处可以自定义插入自己的实现；</li>
<li>Authenticator可能会委托给相应的AuthenticationStrategy进行多Realm身份验证，默认ModularRealmAuthenticator会调用AuthenticationStrategy进行多Realm身份验证；</li>
<li>Authenticator会把相应的token传入Realm，从Realm获取身份验证信息，如果没有返回/抛出异常表示身份验证失败了。此处可以配置多个Realm，将按照相应的顺序及策略进行访问。</li>
</ol>
<h3 id="Authenticator"><a href="#Authenticator" class="headerlink" title="Authenticator"></a>Authenticator</h3><p>Authenticator的职责是验证用户帐号，是Shiro API中身份验证核心的入口点： </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> AuthenticationInfo <span class="title">authenticate</span><span class="params">(AuthenticationToken authenticationToken)</span> <span class="keyword">throws</span> AuthenticationException</span>;</div></pre></td></tr></table></figure>
<p>如果验证成功，将返回AuthenticationInfo验证信息；此信息中包含了身份及凭证；如果验证失败将抛出相应的AuthenticationException实现。</p>
<p>Shiro默认使用一个ModularRealmAuthenticator实例，ModularRealmAuthenticator同样支持单Realm和多Realm。</p>
<p>在一个单Realm程序中，ModularRealmAuthenticator将直接执行单独的Realm，如果配置有两个或以上Realm，将会使用AuthenticationStrategy实例来协调如何进行验证。</p>
<h3 id="AuthenticationStrategy"><a href="#AuthenticationStrategy" class="headerlink" title="AuthenticationStrategy"></a>AuthenticationStrategy</h3><p>SecurityManager接口继承了Authenticator，另外还有一个ModularRealmAuthenticator实现，其委托给多个Realm进行验证，验证规则通过AuthenticationStrategy接口指定，有3个具体的实现：</p>
<table>
<thead>
<tr>
<th style="text-align:center">AuthenticationStrategy</th>
<th style="text-align:center">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">AtLeastOneSuccessfulStrategy(默认)</td>
<td style="text-align:center">如果有一个或多个Realm验证成功，所有的尝试都被认为是成功的，如果没有一个验证成功，则该次尝试失败</td>
</tr>
<tr>
<td style="text-align:center">FirstSuccessfulStrategy</td>
<td style="text-align:center">只有从第一个成功验证的Realm返回的信息会被使用，以后的Realm将被忽略，如果没有一个验证成功，则该次尝试失败</td>
</tr>
<tr>
<td style="text-align:center">AllSuccessfulStrategy</td>
<td style="text-align:center">所有配置的Realm在全部尝试中都成功验证才被认为是成功，如果有一个验证不成功，则该次尝试失败。</td>
</tr>
</tbody>
</table>
<p>你可以自己配置你希望的不同策略：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="section">[main]</span></div><div class="line">...</div><div class="line"><span class="attr">authcStrategy</span> = org.apache.shiro.authc.pam.FirstSuccessfulStrategy</div><div class="line">securityManager.authenticator.authenticationStrategy = $authcStrategy</div><div class="line">...</div></pre></td></tr></table></figure>
<h3 id="Realm-验证的顺序"><a href="#Realm-验证的顺序" class="headerlink" title="Realm 验证的顺序"></a>Realm 验证的顺序</h3><p>和Realm交互的ModularRealmAuthenticator按迭代（iteration）顺序执行ModularRealmAuthenticator可以访问为SecurityManager配置的Realm实例，当尝试一次验证时，它将在集合中遍历，支持对提交的AuthenticationToken处理的每个Realm都将执行Realm的getAuthenticationInfo 方法。</p>
<h4 id="隐含的顺序"><a href="#隐含的顺序" class="headerlink" title="隐含的顺序"></a>隐含的顺序</h4><p>在使用ShiroINI配置文件形式时，你可以按你希望其处理AuthenticationToken的顺序来配置Realm，例如，在shiro.ini中，Realm将按照他们在INI文件中定义的顺序执行。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">blahRealm = com.company.blah.Realm</div><div class="line">fooRealm = com.company.foo.Realm</div><div class="line">barRealm = com.company.another.Realm</div></pre></td></tr></table></figure>
<h4 id="Explicit-Ordering明确的顺序"><a href="#Explicit-Ordering明确的顺序" class="headerlink" title="Explicit Ordering明确的顺序"></a>Explicit Ordering明确的顺序</h4><p>如果你希望明确定义 realm 执行的顺序，不管他们如何被定义，你可以设置 SecurityManager 的 realms 属性，例如，使用上面定义的 realm，但你希望 blahRealm 最后执行而不是第一个：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">securityManager.realms = $fooRealm, $barRealm, $blahRealm</div></pre></td></tr></table></figure>
<blockquote>
<p>当你明确的配置securityManager.realms属性时，只有被引用的realm将为SecurityManager配置，也就是说你可能在INI中定义了5个realm，但实际上只使用了3个。</p>
</blockquote>
<hr>
<h2 id="Final-Tutorial-class"><a href="#Final-Tutorial-class" class="headerlink" title="Final Tutorial class"></a>Final Tutorial class</h2><p>下面你可以自行编写测试代码。假设我们有三个realm：<br>myRealm1： 用户名/密码为lonestarr/vespa时成功，且返回身份/凭据为lonestarr/vespa；<br>myRealm2： 用户名/密码为lonestarr/vespa时成功，且返回身份/凭据为lonestarr/vespa；<br>myRealm3： 用户名/密码为lonestarr/vespa时成功，且返回身份/凭据为lonestarr@163.com/vespa，和myRealm1不同的是返回时的身份变了；</p>
<p>如果配置多个realm，那么所有配置的Realm在全部尝试中都成功验证才被认为是成功。</p>
<p>下面贴出完整代码：</p>
<h3 id="MyRealm1-2-3"><a href="#MyRealm1-2-3" class="headerlink" title="MyRealm1,2,3"></a>MyRealm1,2,3</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">package</span> cn.sqdyy.shiro;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyRealm1</span> <span class="keyword">implements</span> <span class="title">Realm</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="string">"myrealm1"</span>;<span class="comment">// 返回一个唯一的Realm名字</span></div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">// 判断此Realm是否支持此Token</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supports</span><span class="params">(AuthenticationToken token)</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> token <span class="keyword">instanceof</span> UsernamePasswordToken;<span class="comment">// 仅支持UsernamePasswordToken类型的Token</span></div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">// 根据Token获取认证信息</span></div><div class="line">    <span class="function"><span class="keyword">public</span> AuthenticationInfo <span class="title">getAuthenticationInfo</span><span class="params">(AuthenticationToken token)</span> <span class="keyword">throws</span> AuthenticationException </span>&#123;</div><div class="line">        String username = (String) token.getPrincipal();</div><div class="line">        String password = <span class="keyword">new</span> String((<span class="keyword">char</span>[]) token.getCredentials());</div><div class="line">        <span class="keyword">if</span> (!<span class="string">"lonestarr"</span>.equals(username)) &#123;</div><div class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> UnknownAccountException(); <span class="comment">// 如果用户名错误</span></div><div class="line">        &#125;</div><div class="line">        <span class="keyword">if</span> (!<span class="string">"vespa"</span>.equals(password)) &#123;</div><div class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IncorrectCredentialsException(); <span class="comment">// 如果密码错误</span></div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">new</span> SimpleAuthenticationInfo(username, password, getName());</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">// myRealm3 :</span></div><div class="line"><span class="comment">// return new SimpleAuthenticationInfo(username + "@163.com", password, getName());</span></div></pre></td></tr></table></figure>
<h3 id="ini配置文件"><a href="#ini配置文件" class="headerlink" title="ini配置文件"></a>ini配置文件</h3><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="comment"># shiro-authenticator-all-success.ini</span></div><div class="line"><span class="comment">#指定securityManager的authenticator实现  </span></div><div class="line"><span class="attr">authenticator</span>=org.apache.shiro.authc.pam.ModularRealmAuthenticator  </div><div class="line">securityManager.authenticator=$authenticator  </div><div class="line">  </div><div class="line"><span class="comment">#指定securityManager.authenticator的authenticationStrategy  </span></div><div class="line"><span class="attr">allSuccessfulStrategy</span>=org.apache.shiro.authc.pam.AllSuccessfulStrategy  </div><div class="line">securityManager.authenticator.authenticationStrategy=$allSuccessfulStrategy  </div><div class="line"></div><div class="line"><span class="comment">#声明多个realm  </span></div><div class="line"><span class="attr">myRealm1</span>=cn.sqdyy.shiro.MyRealm1</div><div class="line"><span class="attr">myRealm2</span>=cn.sqdyy.shiro.MyRealm2</div><div class="line"><span class="attr">myRealm3</span>=cn.sqdyy.shiro.MyRealm3</div><div class="line">securityManager.realms=$myRealm1,$myRealm3</div></pre></td></tr></table></figure>
<h3 id="测试类AuthenticatorTest"><a href="#测试类AuthenticatorTest" class="headerlink" title="测试类AuthenticatorTest"></a>测试类AuthenticatorTest</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">package</span> cn.sqdyy.shiro.test;</div><div class="line"></div><div class="line"><span class="keyword">import</span> junit.framework.Assert;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AuthenticatorTest</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">login</span><span class="params">(String configFile)</span> </span>&#123;</div><div class="line">        Factory&lt;org.apache.shiro.mgt.SecurityManager&gt; factory = <span class="keyword">new</span> IniSecurityManagerFactory(configFile);</div><div class="line">        org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();</div><div class="line">        SecurityUtils.setSecurityManager(securityManager);</div><div class="line">        Subject subject = SecurityUtils.getSubject();  </div><div class="line">        UsernamePasswordToken token = <span class="keyword">new</span> UsernamePasswordToken(<span class="string">"lonestarr"</span>, <span class="string">"vespa"</span>);  </div><div class="line">        subject.login(token);  </div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="meta">@Test</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testAllSuccessfulStrategyWithSuccess</span><span class="params">()</span> </span>&#123;</div><div class="line">        login(<span class="string">"classpath:shiro-authenticator-all-success.ini"</span>);</div><div class="line">        Subject subject = SecurityUtils.getSubject();</div><div class="line">        <span class="comment">// 得到一个身份集合</span></div><div class="line">        PrincipalCollection principalCollection = subject.getPrincipals();</div><div class="line">        Assert.assertEquals(<span class="number">2</span>, principalCollection.asList().size());</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">// 如果认证失败如账号错误：org.apache.shiro.authc.UnknownAccountException</span></div></pre></td></tr></table></figure>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2017-12-05T09:59:44.484Z" itemprop="dateUpdated">2017年12月5日 17:59</time>
</span><br>


        如要转载请注明出处：<a href="/2017/12/05/shiro03/" target="_blank" rel="external">http://magic_duck.oschina.io/2017/12/05/shiro03/</a>
    </div>
    <footer>
        <a href="http://magic_duck.oschina.io">
            <img src="/img/avatar.jpg" alt="神奇的鸭鸭">
            神奇的鸭鸭
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/安全/">安全</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://magic_duck.oschina.io/2017/12/05/shiro03/&title=《shiro(三) 身份认证》 — 神奇的鸭鸭の码农库&pic=http://magic_duck.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://magic_duck.oschina.io/2017/12/05/shiro03/&title=《shiro(三) 身份认证》 — 神奇的鸭鸭の码农库&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://magic_duck.oschina.io/2017/12/05/shiro03/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《shiro(三) 身份认证》 — 神奇的鸭鸭の码农库&url=http://magic_duck.oschina.io/2017/12/05/shiro03/&via=http://magic_duck.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://magic_duck.oschina.io/2017/12/05/shiro03/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between flex-row-reverse">
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/12/05/shiro02/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">shiro(二) 架构和配置</h4>
      </a>
    </div>
  
</nav>



    







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        我只要一角钱~ ~
        <i class="icon icon-quote-right"></i>
    </h3>
    <ul class="reward-items">
        
        <li>
            <img src="/img/wechat.png" title="微信打赏二维码" alt="微信打赏二维码">
            <p>微信</p>
        </li>
        

        
        <li>
            <img src="/img/alipay.jpg" title="支付宝打赏二维码" alt="支付宝打赏二维码">
            <p>支付宝</p>
        </li>
        
    </ul>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            <span><a href="" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            <span>博客内容遵循 <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p>
            <span>Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://git.oschina.net/z77z" target="_blank">邹海清</a></span>
            <span>神奇的鸭鸭の码农库 &copy; 2017</span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://magic_duck.oschina.io/2017/12/05/shiro03/&title=《shiro(三) 身份认证》 — 神奇的鸭鸭の码农库&pic=http://magic_duck.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://magic_duck.oschina.io/2017/12/05/shiro03/&title=《shiro(三) 身份认证》 — 神奇的鸭鸭の码农库&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://magic_duck.oschina.io/2017/12/05/shiro03/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《shiro(三) 身份认证》 — 神奇的鸭鸭の码农库&url=http://magic_duck.oschina.io/2017/12/05/shiro03/&via=http://magic_duck.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://magic_duck.oschina.io/2017/12/05/shiro03/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=http://magic_duck.oschina.io/2017/12/05/shiro03/" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };



lazyScripts.push('//s95.cnzz.com/z_stat.php?id=1261081671&web_id=1261081671')

</script>

<script src="/js/main.min.js?v=1.4.3"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/js/search.min.js?v=1.4.3" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>


</body>
</html>
